<template>
  <view class="container">
	 <view class="container1">
	  <!-- 视频文件 -->
	  <text class="textTitle" v-model="videoName">{{videoSrc}}</text>
	  <!-- 上传图标 -->
	  <button class="upload"  @click="chooseVideo">选择视频</button>
	  </view>
	  <view class="container1">
	   <!-- 封面文件 -->
	   <text class="textTitle" v-model="coverName">{{imageSrc}}</text>
	   <!-- 上传图标 -->
	   <button class="upload"  @click="chooseImage">选择封面</button>
	   </view>
	   <!-- 分类栏 -->
	   <scroll-view class="category" scroll-x>
	     <text class="item" v-for="(item, index) in categories" :key="index" :class="{active: index === active}" @click="select(index)">{{item.name}}</text>
	   </scroll-view>
    <!-- 视频预览 -->
    <video class="video" :src="videoSrc" controls></video>
    <!-- 视频标题 -->
    <input class="title" v-model="title" placeholder="请输入视频标题"></input>
    <!-- 视频描述 -->
    <textarea class="desc" v-model="desc" placeholder="请输入视频描述"></textarea>
    <!-- 发布按钮 -->
    <button class="button" @click="publish">发布</button>
	   <!-- <button class="button" @click="beforepublish">获取凭证</button> -->

  </view>
</template>

<script>

export default {
  data() {
    return {
		active: 0,
		
		// 分类数据
		categories: [
		  {
		    name: "娱乐",
				  type:"ENTERTAINMENT",
		  },
		  {
		    name: "生活",
				  type:"LIFE",
		  },
		  {
		    name: "学习",
				  type:"STUDY",
		  },
		
		],
	
      // 视频源
	  videoName: "videoName",
      videoSrc: "视频文件名", //"https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4",
      // 视频封面
	  coverName: "coverName",
	  imageSrc: "封面文件名",
	  // 视频标题
      title: "",
      // 视频描述
      desc: "",
	  type: "LIFE",
	  
	  
	videoUploadInfo: {  
		tmpSecretId: "",
		tmpSecretKey: "",
		sessionToken: "",
		uploadUrl: "",
		uploadPath: "",
	},
	videoRemoteURL: "",
	  
	imageUploadInfo: {
	  	tmpSecretId: "",
	  	tmpSecretKey: "",
	  	sessionToken: "",
	  	uploadUrl: "",
		uploadPath: "",
	},
	imageRemoteURL: "",
	
    };
  },
  methods: {
	  // 选择分类
	  select(index) {
	    this.active = index;
	    this.type = this.categories[index].type
	    console.log(this.type)
		uni.showToast({
		  title: this.categories[index].name,
		  icon: "none"
		});
	  },
	  
	  getImageFileFromUrl(url, imageName, callback) {
	    fetch(url)
	      .then((res) => {
	        return res.blob();
	      })
	      .then((blob) => {
	        let imgFile = new File([blob], imageName, { type: "image/jpeg" });
	        callback(imgFile);
	      });
	  },
	  
	  
	uploadimage(tmpSecretId, tmpSecretKey, sessionToken, uploadUrl, uploadPath, file_path) {
	  return new Promise((resolve, reject) => {
		var COS = require('cos-wx-sdk-v5');
		let that = this;
		let cosf = new COS({
		  SecretId: tmpSecretId,
		  SecretKey: tmpSecretKey,
		  SecurityToken: sessionToken,
		  
		});

		console.log("图片地址：" + file_path);
		cosf.postObject({
		  Bucket: 'gualiguali-1308905817',
		  Region: 'ap-beijing',
		  Key: uploadPath + "/.jpg",
		  FilePath: file_path,
		}, function(err, data) {
		  if (err) {
			console.error(err);
			reject(err);
		  } else {
			console.log('function ---->', err || data);
			that.imageRemoteURL = 'https://'+data.Location;
			console.log(that.imageRemoteURL);
			resolve();
		  }
		});
	  });
	},

	uploadvideo(tmpSecretId, tmpSecretKey, sessionToken, uploadUrl, uploadPath, file_path) {
	  return new Promise((resolve, reject) => {
		var COS = require('cos-wx-sdk-v5');
		let that = this;
		let cosf = new COS({
		  SecretId: tmpSecretId,
		  SecretKey: tmpSecretKey,
		  SecurityToken: sessionToken
		});

		console.log("视频地址：" + file_path);
		cosf.postObject({
		  Bucket: 'gualiguali-1308905817',
		  Region: 'ap-beijing',
		  Key: uploadPath + "/.mp4",
		  FilePath: file_path,
		}, function(err, data) {
		  if (err) {
			console.error(err);
			reject(err);
		  } else {
			console.log('function ---->', err || data);
			that.videoRemoteURL = 'https://'+data.Location;
			console.log(that.videoRemoteURL);
			resolve();
		  }
		});
	  });
	},

	reportURL(){
		uni.request({
		  method: 'POST',
		  url: "http://47.97.114.13:8080/api/video",
		  header: {
	  			"Authorization": this.$store.state.token,
	  			// this.$store.state.token,
		  },
		data: {
			coverUrl: this.imageRemoteURL,
			videoUrl: this.videoRemoteURL,
			title: this.title,
			introduction: this.desc,
			type: this.type,
		},
		  success: (res) => {
		    console.log("汇报视频url");
		    console.log(res);
			  		  if(res.data.success === true)
			  		  {
			  			  uni.showToast({
			  			    title: "上传视频成功",
			  			    icon: "success"
			  			  });
			  		  }
					  else{
						  uni.showModal({
						  				title: "提示",
						  				content: "上传失败："+res[1].data.message,
						  				showCancel:false,
						  				success: function (res) {
						  					if (res.confirm) {
						  						console.log('用户点击确定');
						  					} else if (res.cancel) {
						  						console.log('用户点击取消');
						  					}
						  				}
						  			});
					  }
		  },
		  fail: (err) => {
		    reject(err);
		  }
		});
	},

		  
		  
	//获取凭证
	beforePublish() {
  console.log("获取视频凭证");
  return new Promise((resolve, reject) => {
    // 获取视频凭证
    uni.request({
      method: 'GET',
      url: "http://47.97.114.13:8080/api/video/file/credential?" + this.title,
      header: {
	  			"Authorization": this.$store.state.token,
	  			// this.$store.state.token,
      },
      data: {
        filename: this.title
      },
      success: (res) => {
        console.log("获取视频凭证");
        this.videoUploadInfo = res.data.data;
        console.log(this.videoUploadInfo);
        resolve();
      },
      fail: (err) => {
        reject(err);
      }
    });
  })
  .then(() => {
    console.log("获取照片凭证");
    return new Promise((resolve, reject) => {
      // 获取照片凭证
      uni.request({
        method: 'GET',
        url: "http://47.97.114.13:8080/api/video/cover/credential?" + this.title,
        header: {
	  			"Authorization": this.$store.state.token,
	  			// this.$store.state.token,
        },
        data: {
          filename: this.title
        },
        success: (res) => {
          console.log("获取照片凭证");
          this.imageUploadInfo = res.data.data;
          console.log(this.imageUploadInfo);
          resolve();
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  })
  .then(() => {
      return this.pushData(); // 返回pushData的Promise结果
    })
  .catch((err) => {
    console.error(err);
  });
},
	// 发布视频
	async pushData() {
		
	  console.log("publishing");
	  return new Promise(async (resolve, reject) => {
	    // if (this.videoSrc && this.imageSrc && this.title && this.desc) {
	    if (true) {
	      uni.showToast({
	        title: "正在发布",
	        icon: "none"
	      });
	
	      //上传image
	      if (this.imageUploadInfo.sessionToken != "" && this.videoUploadInfo.sessionToken != "") {
	        await this.uploadimage(this.imageUploadInfo.tmpSecretId, this.imageUploadInfo.tmpSecretKey, this.imageUploadInfo.sessionToken, this.imageUploadInfo.uploadUrl, this.imageUploadInfo.uploadPath, this.imageSrc);
	        await this.uploadvideo(this.videoUploadInfo.tmpSecretId, this.videoUploadInfo.tmpSecretKey, this.videoUploadInfo.sessionToken, this.videoUploadInfo.uploadUrl, this.videoUploadInfo.uploadPath, this.videoSrc);
	      }
	
	      resolve(); // 表示前面的操作已完成
	    } else {
	      uni.showToast({
	        title: "请填写完整信息",
	        icon: "none"
	      });
	      reject(new Error("信息不完整")); // 如果信息不完整，则返回错误
	    }
	  })
	  .then(() => {
	    return new Promise((resolve, reject) => {
	      this.reportURL()
		})
	  })
	  .catch((err) => {
	    console.error(err);
	  });
	},
	
	
	publish(){
		this.beforePublish()
	},
	
	
    // 选择视频
    chooseVideo() {
      uni.chooseVideo({
        sourceType: ["album", "camera"],
        maxDuration: 60,
        camera: "back",
        success: res => {
			//console.log(res)
          this.videoSrc = res.tempFilePath;
		console.log("视频地址："+this.videoSrc)
        }
      });
    },
	chooseImage() {
	  uni.chooseImage({
		count: 1,
	    sourceType: ["album", "camera"],
	    success: res => {

	      this.imageSrc = res.tempFilePaths[0];
		console.log("图片地址："+ this.imageSrc)
	    }
	  });
	}
  }
};
</script>

<style>

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.container1 {
  display: flex;
  align-items: center;
  width :80%;
}

.textTitle{
	width :65%;
	height :60rpx;
	margin-top :20rpx;
	border :1rpx solid #cccccc;
	border-radius :10rpx;
	padding-left :10rpx;
	padding-right :10rpx;
	font-size :28rpx;
	padding-top: 20rpx;
}
.video {
  width: 80%;
  height: 400rpx;
  margin-top: 20rpx;
}
.upload {
   width :35%;
   height :80rpx;
	margin-left: 5rpx;
	margin-top: 20rpx;
}
.title {
   width :80%;
   height :80rpx;
   margin-top :20rpx;
   border :1rpx solid #cccccc;
   border-radius :10rpx;
   padding-left :10rpx;
   padding-right :10rpx;
   font-size :28rpx
}
.desc {
   width :80%;
   height :200rpx;
   margin-top :20rpx;
   border :1rpx solid #cccccc;
   border-radius :10rpx;
   padding-left :10rpx;
   padding-right :10rpx;
   font-size :28rpx
}
.button {
   width :80%;
   height :80rpx;
   margin-top :20rpx;
   background-color :#1aad19;
   color :#ffffff;
   border-radius :10rpx;
   font-size :32rpx;
   text-align :center;
   line-height :80rpx
}
.category {
   display :flex;
   text-align: center;
   width :100%;
   height :80rpx;
   background-color :#ffffff;
   margin-top: 10rpx;
}
.item {
   font-size :35rpx;
   margin :10rpx;
   color :#999999
}
.active {
   color :#ff0000
}
</style>
